<template>
  <div class="login-page">
    <!-- //标题 -->
    <van-nav-bar title="面经登入"/>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
     <van-field
    v-model="username"
    name="username"
    label="用户名"
    placeholder="用户名"
    :rules="userRules"
   />
  <van-field
    v-model="password"
    type="password"
    name="password"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' },{pattern: /^\S{6,10}$/, message: '请输入6-10位的密码' }]"
  />
  <div style="margin: 16px;">
    <van-button  block type="info" native-type="submit">登入</van-button>
  </div>
    </van-form>
    <!-- 超链接 -->
     <router-link class="link" to="/register">还没有账号，去注册</router-link>
  </div>
</template>

<script>
import { loginApi } from '@/api/user'
import 'vant/lib/button/style/less'
export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: '',
      userRules: [
        { required: true, message: '请填写用户名' },
        { pattern: /^\w{6,10}$/, message: '请输入6-10位的用户名' }
      ]
    }
  },
  methods: {
    async onSubmit (values) {
      try {
        const res = await loginApi(values)
        this.$toast('登入成功')
        localStorage.setItem('mobie-token', res.data.data.token)
        this.username = this.password = ''
        this.$router.push('/article')
      } catch (err) {
        console.log(err)
        if (err.response) {
          this.$toast(err.response.data.message)
        } else {
          this.$toast('登入失败')
        }
      }
    }
  }

}
</script>

<style lang="less" scoped>
.link {
  float: right;
  margin-right: 20px;
  font-size: 15px;
  color: #1989fa;
  text-decoration: underline;
}
</style>
